import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:go_router/go_router.dart';
import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:leader_doctor_flutter/common/http/api.dart';
import 'package:leader_doctor_flutter/common/http/http_client.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/common/utils/log_utils.dart';
import 'package:leader_doctor_flutter/common/utils/reg_exp_utils.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/common/widget/verify_code_exception_help.widget.dart';
import 'package:leader_doctor_flutter/plugins/plugins_messages.g.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';
import 'dart:async';

import 'package:netease_meeting_ui/meeting_ui.dart';

import '../../../common/utils/string_utils.dart';

/// @Author lixiaobin
/// @Date 2023/12/5
/// @Description 修改登录密码
class ModifyPassPage extends StatefulWidget {
  const ModifyPassPage({super.key});

  @override
  State<ModifyPassPage> createState() => _ModifyPassPageState();
}

class _ModifyPassPageState extends State<ModifyPassPage> {
  final _smsTextEditingController = TextEditingController();
  final _pwdTextEditingController = TextEditingController();

  bool _isShowEye = false;
  int _countValue = 0;
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    _smsTextEditingController.addListener(() {
      setState(() {});
    });
    _pwdTextEditingController.addListener(() {
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    var isSelectBtn = _smsTextEditingController.text.isNotEmpty && _pwdTextEditingController.text.isNotEmpty;
    return Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: CommWidget.getCommAppbar(context),
        body: Container(
          width: double.infinity,
          height: double.infinity,
          color: ColorRes.white,
          child: Column(children: [
            // CommWidget.buildLine(height: 12.w, color: ColorRes.colorf5f7f9),
            Expanded(
                child: Container(
                    padding: EdgeInsets.only(top: 0.w, left: 12.w, right: 12.w, bottom: 12.w),
                    width: double.infinity,
                    height: double.infinity,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        SizedBox(
                            height: 50.w,
                            child: Row(children: [
                              Expanded(
                                child: Text(
                                  App.instance.userInfo?.phone ?? '',
                                  style: TextStyle(
                                      color: ColorRes.color333333, fontWeight: FontWeight.bold, fontSize: 15.sp),
                                ),
                              ),
                            ])),
                        CommWidget.buildLine(),

                        Container(
                          height: 56.w,
                          width: double.infinity,
                          child: Row(
                            children: [
                              Expanded(
                                  child: TextField(
                                controller: _smsTextEditingController,
                                inputFormatters: [
                                  LengthLimitingTextInputFormatter(6),
                                  FilteringTextInputFormatter.allow(RegExp(r'[0-9]'))
                                ],
                                decoration: const InputDecoration(hintText: '请输入验证码', border: InputBorder.none),
                              )),
                              GestureDetector(
                                onTap: () => _getSms(),
                                child: Container(
                                    height: 30.w,
                                    padding: EdgeInsets.only(left: 10.w, right: 10.w),
                                    alignment: Alignment.center,
                                    child: Text(_countValue == 0 ? '获取验证码' : '$_countValue秒后可重新发送',
                                        style: TextStyle(
                                            fontWeight: FontWeight.bold,
                                            color: _countValue == 0 ? ColorRes.colorMain : ColorRes.color9A9A9A,
                                            fontSize: 15.sp))),
                              )
                            ],
                          ),
                        ),

                        CommWidget.buildLine(),
                        SizedBox(
                          height: 50.w,
                          width: double.infinity,
                          child: Row(
                            children: [
                              Expanded(
                                  child: TextField(
                                controller: _pwdTextEditingController,
                                inputFormatters: [
                                  LengthLimitingTextInputFormatter(12),
                                  FilteringTextInputFormatter.allow(RegExp(r'[0-9a-zA-Z]'))
                                ],
                                obscureText: !_isShowEye,
                                decoration:
                                    const InputDecoration(hintText: '请输入6-12位由数字和字母组成的密码', border: InputBorder.none),
                              )),
                              GestureDetector(
                                  onTap: () {
                                    _isShowEye = !_isShowEye;
                                    setState(() {});
                                  },
                                  child:
                                      ImageLoader.loadAsset(_isShowEye ? 'icon_eye.webp' : 'icon_eye_close.webp', 20.w))
                            ],
                          ),
                        ),
                        CommWidget.buildLine(),
                        SizedBox(
                          height: 10.w,
                        ),
                        VerifyCodeExceptionHelpWidget(),
                        SizedBox(
                          height: 52.w,
                        ),
                        // CommWidget.buildBtn1('确定', () => _updatePwdBySmsCode(), isSelect: isSelectBtn),
                        CommWidget.customBuildBtn("确定", () {
                          _updatePwdBySmsCode();
                        }, ColorRes.colorMain, ColorRes.colorB8B3FA, 6.w, isSelect: isSelectBtn),
                        // Expanded(
                        //     child: GestureDetector(
                        //         onTap: () {
                        //           NativeInterface().call(
                        //               App.instance.serviceInfo?.phone ?? "");
                        //         },
                        //         child: Column(
                        //           mainAxisAlignment: MainAxisAlignment.end,
                        //           crossAxisAlignment: CrossAxisAlignment.start,
                        //           children: [
                        //             Row(
                        //               mainAxisAlignment:
                        //                   MainAxisAlignment.center,
                        //               children: [
                        //                 Text('  客服电话：',
                        //                     style: TextStyle(
                        //                         color: ColorRes.color666666,
                        //                         fontSize: 12.sp)),
                        //                 Text(
                        //                     App.instance.serviceInfo?.phone ??
                        //                         '',
                        //                     style: TextStyle(
                        //                         color: ColorRes.color0065ff,
                        //                         fontSize: 12.sp)),
                        //               ],
                        //             ),
                        //             Row(
                        //               mainAxisAlignment:
                        //                   MainAxisAlignment.center,
                        //               children: [
                        //                 Text('客服工作时间：',
                        //                     style: TextStyle(
                        //                         color: ColorRes.color666666,
                        //                         fontSize: 12.sp)),
                        //                 Text(
                        //                     '工作日${App.instance.serviceInfo?.workingTime ?? ''}',
                        //                     style: TextStyle(
                        //                         color: ColorRes.color666666,
                        //                         fontSize: 12.sp)),
                        //               ],
                        //             )
                        //           ],
                        //         ))),
                        // SizedBox(
                        //   height: 20.w,
                        // ),
                      ],
                    )))
          ]),
        ));
  }

  @override
  void dispose() {
    // 组件销毁时判断Timer是否仍然处于激活状态，是则取消
    if (_timer?.isActive == true) {
      _timer?.cancel();
    }
    super.dispose();
  }

  /// 启动Timer
  _startTimer() {
    const Duration duration = Duration(seconds: 1);
    cancelTimer();

    _timer = Timer.periodic(duration, (timer) {
      _countValue -= 1;
      Log.d(_countValue);
      if (_countValue <= 0) {
        cancelTimer();
      }
      setState(() {});
    });
  }

  void cancelTimer() {
    if (_timer != null) {
      _timer?.cancel();
    }
  }

  /// 获取验证码
  _getSms() async {
    if (_countValue > 0) return;
    var phone = App.instance.userInfo?.phone;
    if (phone == null || phone.isEmpty == true) return;
    var httpRequest = HttpRequest(Api.sendSms, body: {
      'phone': phone,
      "purpose": '修改密码',
    });
    var httpResponse = await HttpClient.post(httpRequest);
    var serviceResult = ServiceResult<String?>.simple(httpResponse);
    if (serviceResult.success) {
      _countValue = 60;
      _startTimer();
    }
    Fluttertoast.showToast(msg: serviceResult.responseMsg ?? "");
  }

  /// 修改密码
  _updatePwdBySmsCode() async {
    // 隐藏键盘
    FocusScope.of(context).unfocus();
    FocusScope.of(context).requestFocus(FocusNode()); // 阻止焦点传递
    var smsCode = _smsTextEditingController.text;
    var pwd = _pwdTextEditingController.text;
    if (smsCode.isEmpty) {
      Fluttertoast.showToast(msg: "请输入验证码");
      return;
    }
    if (pwd.length < 6 || pwd.length > 12) {
      Fluttertoast.showToast(msg: "请输入6-12位由数字和字母组成的密码");
      return;
    }
    if (!RegExpUtils.isAlphaNumeric(pwd)) {
      Fluttertoast.showToast(msg: "请输入6-12位由数字和字母组成的密码");
      return;
    }
    var id = App.instance.userInfo?.id;
    if (id == null || id.isEmpty == true) return;
    _countValue = 60;
    var httpRequest = HttpRequest(Api.updatePwdBySmsCode, body: {
      "userId": id,
      'password': StringUtils.dartMd5(pwd),
      "verficationCode": smsCode,
    });
    var httpResponse = await HttpClient.post(httpRequest);
    var serviceResult = ServiceResult<String?>.simple(httpResponse);
    if (serviceResult.success) {
      Fluttertoast.showToast(msg: "修改成功，请重新登录！");
      NativeInterface().confirmLogOut();
    } else {
      Fluttertoast.showToast(msg: serviceResult.responseMsg ?? "");
    }
  }
}
